<template>
	<!-- 用户信息 -->
	<el-dropdown>
		<img :src="store.user.imageUrl" alt="" />
		<template #dropdown>
			<el-dropdown-menu>
				<el-dropdown-item
					@click="
						showDialog('个人信息');
						dialogVisible = true;
					"
					>个人信息</el-dropdown-item
				>
				<el-dropdown-item
					@click="
						showDialog('修改手机号&密码');
						dialogVisible2 = true;
					"
					>修改手机号&密码</el-dropdown-item
				>
				<!-- <el-dropdown-item disabled>Action 4</el-dropdown-item> -->
				<el-dropdown-item divided @click="dark">退出登录</el-dropdown-item>
			</el-dropdown-menu>
		</template>
	</el-dropdown>

	<!-- 用户个人信息 -->
	<el-dialog v-model="dialogVisible" :title="hader" width="35%">
		<div class="contaier">
			<div class="text">头像(点击更换)</div>
			<el-upload
				ref="uploadRef"
				:auto-upload="false"
				class="avatar-uploader"
				method="PUT"
				name="image"
				:headers="{ Authorization: store.user.token }"
				:action="HTTP + '/user/updateUserImage'"
				:show-file-list="false"
				:on-change="handleAvatarChange"
				:before-upload="beforeAvatarUpload"
				:on-success="handleAvatarSuccess"
			>
				<img
					v-if="userData?.userPersonVo.imageUrl"
					:src="userData?.userPersonVo.imageUrl"
					class="avatar"
				/>
				<el-icon v-else class="avatar-uploader-icon">
					<Plus />
				</el-icon>
			</el-upload>
			<div class="text">ID</div>
			<el-input
				disabled
				style="width: 70%"
				v-model="input"
				placeholder="请输入ID"
			/>
			<div class="text">姓名</div>
			<el-input
				disabled
				style="width: 70%"
				v-model="input2"
				placeholder="请输入昵称"
			/>
			<div class="text">组织ID</div>
			<el-input
				disabled
				style="width: 70%"
				v-model="input3"
				placeholder="请输入组织"
			/>
			<div class="text">组织名称</div>
			<el-input disabled style="width: 70%" v-model="input4" placeholder="组织" />
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" :disabled="input == ''" @click="setuserData">
					确认
				</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 修改密码和手机号 -->
	<el-dialog v-model="dialogVisible2" :title="hader" width="30%">
		<div class="contaier">
			<!-- 表单验证 -->
			<el-form
				style="flex: 1; display: flex; flex-direction: column"
				ref="ruleFormRef"
				:rules="rules"
				:model="form"
				label-width="80px"
				label-position="left"
			>
				<el-form-item label="手机号" prop="phone">
					<el-input
						style="width: 70%"
						v-model="form.phone"
						placeholder="请输入手机号"
					/>
				</el-form-item>
				<el-form-item label="旧密码" prop="password">
					<el-input
						style="width: 70%"
						type="text"
						autocomplete="off"
						v-model="form.password"
						placeholder="请输入旧密码"
					/>
				</el-form-item>
				<el-form-item label="新密码" prop="newpassword">
					<el-input
						style="width: 70%"
						type="text"
						autocomplete="off"
						v-model.number="form.newpassword"
						placeholder="请输入新密码"
					/>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible2 = false">取消</el-button>
				<el-button
					type="primary"
					:disabled="input == ''"
					@click="submitForm(ruleFormRef)"
				>
					确认
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useStore } from "@/stores/counter";
import { showUserMessage, updateUserMessage } from "@/request/api";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadInstance, FormInstance } from "element-plus";
import type { userData } from "@/type/user";
import { md5 } from "@/hooks/index";
let HTTP = import.meta.env.VITE_HTTP;
const store = useStore();
const data = defineProps<{
	dark: Function;
	deleteUser: Function;
}>();
let dialogVisible = ref<boolean>(false);
let dialogVisible2 = ref<boolean>(false);

let hader = ref<string>("个人信息"); //标题
let input = ref<string>(""); //昵称
let input2 = ref<string>(""); //昵称
let input3 = ref<number>(0); //昵称
let input4 = ref<string>(""); //昵称
showUserMessage().then((res) => {
	userData.value = res.data;
	input.value = res.data.userPersonVo.id;
	input2.value = res.data.userPersonVo.name;
	input3.value = res.data.userPersonVo.organizationId;
	input4.value = res.data.hierarchy[1]
		? res.data.hierarchy[0] + "-" + res.data.hierarchy[1]
		: res.data.hierarchy[0];
	store.user.imageUrl = res.data.userPersonVo.imageUrl;
});

//打开个人信息弹窗
const showDialog = (setHader: any) => {
	hader.value = setHader;
};
let userData = ref<userData>();

//头像上传
const uploadRef = ref<UploadInstance>();
//当选择文件时触发
const handleAvatarChange: UploadProps["onSuccess"] = (response, uploadFile) => {
	if (beforeAvatarUpload(response.raw))
		userData.value!.userPersonVo.imageUrl = URL.createObjectURL(response.raw);
};
//上传成功回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
	response,
	uploadFile
) => {
	console.log(response, uploadFile);

	console.log(URL.createObjectURL(uploadFile.raw!), uploadFile.raw);

	store.user.imageUrl = URL.createObjectURL(uploadFile.raw!);
	ElMessage.success(response.data);
	dialogVisible.value = false;
};
//图片验证
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
	if (!(rawFile.type == "image/jpeg" || rawFile.type == "image/jpg")) {
		ElMessage.error("请上传jpeg和jpg格式图片");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("Avatar picture size can not exceed 2MB!");
		return false;
	}
	return true;
};
//修改用户数据
const setuserData = () => {
	uploadRef.value!.submit();
	dialogVisible.value = false;
};

//表单校验
const form: any = reactive({
	password: "",
	phone: "",
	newpassword: "",
});
const ruleFormRef = ref<FormInstance>();
const validatePass = (rule: any, value: any, callback: any) => {
	//查看用户手机号是否合法
	var re =
		/^1((3[\d])|(4[5,6,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[1-3,5-8])|(9[1,8,9]))\d{8}$/;
	if (re.test(value + "")) {
		callback();
	} else {
		callback(new Error("手机号不合法"));
	}
};
const validatePass2 = (rule: any, value: any, callback: any) => {
	//查看用户手机号是否合法
	let password = md5(form.password);
	var re = /^\d{5,11}$/;
	if (!re.test(value + "")) {
		return callback(new Error("请输入5到11位的数字"));
	} else if (password != userData.value?.userPersonVo.password) {
		return callback(new Error("旧密码输入错误"));
	} else {
		callback();
	}
};
const validatePass3 = (rule: any, value: any, callback: any) => {
	//查看用户手机号是否合法
	var re = /^\d{5,11}$/;
	if (re.test(value + "")) {
		callback();
		return;
	} else {
		callback(new Error("请输入5到11位的数字"));
	}
};
const rules = reactive({
	password: [
		{ required: true, message: "密码不能为空", trigger: "blur" },
		{ validator: validatePass2, trigger: "blur" },
	],
	phone: [
		{ required: true, message: "手机号不能为空", trigger: "blur" },
		{ min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" },
		{ validator: validatePass, trigger: "blur" },
	],
	newpassword: [
		{ required: true, message: "密码不能为空", trigger: "blur" },
		{ validator: validatePass3, trigger: "blur" },
	],
});
//开始验证表单
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			//开始进行登录，服务端验证

			updateUserMessage({
				password: form.newpassword,
				phone: form.phone,
			}).then((res) => {
				ElMessage.success(res.data);
				data.deleteUser();
			});
		} else {
		}
	});
};
</script>

<style lang="less" scoped>
// .contaier {}

img {
	height: 40px;
	aspect-ratio: 1/1;
	border-radius: 50%;
}

.text {
	margin: 1vh 0px;
}

.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
